package com.hy.service;

import com.hy.Result.ResponseResult;
import com.hy.medicine.UserAddress;
import com.hy.medicine.region.Province;
import com.hy.medicine.region.City;
import com.hy.medicine.region.District;
import com.hy.mapper.UserAddressMapper;
import com.hy.mapper.RegionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户地址服务实现类
 */
@Service
public class UserAddressServiceImpl implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RegionService regionService;

    @Override
    public ResponseResult getAddressByUserId(Long userId) {
        return ResponseResult.okResult(userAddressMapper.selectByUserId(userId));
    }

    @Override
    public UserAddress getAddressById(Long addressId) {
        return userAddressMapper.selectById(addressId);
    }

    @Override
    public UserAddress getDefaultAddress(Long userId) {
        return userAddressMapper.selectDefaultByUserId(userId);
    }

    @Override
    @Transactional
    public Long addAddress(UserAddress address) {
        // 验证省市区ID的有效性
        validateAddress(address);

        // 如果是第一个地址，自动设置为默认地址
        List<UserAddress> existingAddresses = userAddressMapper.selectByUserId(address.getUserId());
        if (existingAddresses.isEmpty()) {
            address.setIsDefault(true);
        }

        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.getIsDefault()) {
            userAddressMapper.clearDefaultAddress(address.getUserId());
        }

        userAddressMapper.insert(address);
        return address.getAddressId();
    }

    @Override
    @Transactional
    public boolean updateAddress(UserAddress address) {
        // 验证省市区ID的有效性
        validateAddress(address);

        // 如果设置为默认地址，先将其他地址设为非默认
        if (address.getIsDefault()) {
            userAddressMapper.clearDefaultAddress(address.getUserId());
        }

        return userAddressMapper.update(address) > 0;
    }

    @Override
    public boolean deleteAddress(Long addressId, Long userId) {
        return userAddressMapper.delete(addressId, userId) > 0;
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Long addressId, Long userId) {
        // 先将所有地址设置为非默认
        userAddressMapper.clearDefaultAddress(userId);

        // 再将指定地址设置为默认
        return userAddressMapper.setDefault(addressId, userId) > 0;
    }

    /**
     * 验证地址信息
     */
    private void validateAddress(UserAddress address) {
        if (address.getProvinceId() == null || address.getCityId() == null || address.getDistrictId() == null) {
            throw new IllegalArgumentException("省市区信息不完整");
        }

        // 验证省市区ID的有效性
        Province province = regionService.getProvinceById(address.getProvinceId());
        if (province == null) {
            throw new IllegalArgumentException("无效的省份ID");
        }

        City city = regionService.getCityById(address.getCityId());
        if (city == null || !city.getProvinceId().equals(address.getProvinceId())) {
            throw new IllegalArgumentException("无效的城市ID");
        }

        District district = regionService.getDistrictById(address.getDistrictId());
        if (district == null || !district.getCityId().equals(address.getCityId())) {
            throw new IllegalArgumentException("无效的区县ID");
        }

        if (address.getName() == null || address.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("收货人姓名不能为空");
        }
        if (address.getPhone() == null || !address.getPhone().matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("手机号格式不正确");
        }
        if (address.getDetail() == null || address.getDetail().trim().isEmpty()) {
            throw new IllegalArgumentException("详细地址不能为空");
        }
    }
}
